package com.itheima.contoller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @param
 * @return
 */
@WebServlet("/jsonServlet")
public class JsonServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   /*     *//*获取前端发送的请求参数，参数为json格式的字符串*//*
        String userStr = req.getParameter("user");
        //将json格式的字符串转换为对象
        ObjectMapper om=new ObjectMapper();
        User user = om.readValue(userStr, User.class);
        System.out.println("user = " + user);*/
        /*现在再向前端写回json格式的字符串，把对象转成json的字符串，看前端怎么处理*/
        ObjectMapper om=new ObjectMapper();
        List<User> list = new ArrayList<>();
        User user1 = new User(null, "黄金标", "22222");
        User user2 = new User(null, "白翻译", "33333");
        User user3 = new User(null, "秃三炮", "44444");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        String s = om.writeValueAsString(list);
        System.out.println("s = " + s);
        resp.setContentType("text/json;charset=UTF-8");
        resp.getWriter().write(s);
    }
}
